package cn.jisol.ngame.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.logging.*;

/**
 * 简单的日志工具类
 */
public class JLoggerUtil {

    public static Logger file(String key,String path,String file){

        Logger log = Logger.getLogger(key);
        log.setLevel(Level.ALL);

        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setLevel(Level.ALL);
        log.addHandler(consoleHandler);

        FileHandler fileHandler = null;

        try {
            //创建文件
            File fi = new File(path);
            if ((fi.exists()) && (fi.isDirectory())) {
                file = path + File.separator + file;
            } else if (!fi.exists()) {
                try {
                    fi.mkdirs();
                    file = path + File.separator + file;
                } catch (Exception localException) {}
            }

            fileHandler = new FileHandler(file, true);//true表示日志内容在文件中追加
            fileHandler.setLevel(Level.ALL);//级别为ALL，记录所有消息
            fileHandler.setFormatter(new Formatter() {
                private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                public String format(LogRecord record) {
                    StringBuilder sb = new StringBuilder();
                    String dataFormat = this.sdf.format(Long.valueOf(record.getMillis()));
                    sb.append(dataFormat).append(" ");
                    sb.append("level:").append(record.getLevel()).append(" ");
                    sb.append(record.getMessage()).append("\n");
                    return sb.toString();
                }
            });

            log.addHandler(fileHandler);

        } catch (Throwable e) {
            System.out.println("创建文件失败！" + e.getMessage());
            return null;
        }

        return log;

    }

}
